﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
//
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
//
// Mp3Cleaner, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//
namespace Mp3Cleaner
{
    public partial class MainWindow : Window
    {
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        private void afterLoad(bool isLoadNewFile)
        {
            button_100.IsEnabled = false;
            button_200.IsEnabled = false;
            button_300.IsEnabled = false;
            button_400.IsEnabled = false;
            //
            isTrackMuliplied = false;
            //
            if (isLoadNewFile)
            {
                checkBox_RemoveCommon.IsChecked = true;
                isTrackMuliplied = false;
            }
            else
            {
                checkBox_RemoveCommon.IsChecked = !isTrackMuliplied;
            }
            //
            //
        }

        private void afterClean()
        {
            button_100.IsEnabled = true;
            button_200.IsEnabled = true;
            button_300.IsEnabled = true;
            button_400.IsEnabled = true;
        }
        private void afterWrite()
        {
            //checkBox_RemoveCommon.Checked = true;
        }
        //
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        //
        private string getVersionInfo()
        {
            //
            string cc = System.Globalization.CultureInfo.CurrentCulture.TextInfo.CultureName;
            //
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
            {
                //działa tylko na zainstalowanym sieciowo programie!
                return string.Format("Version: {0} ({1})", System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion, cc);
            }
            //
            Assembly ass = Assembly.GetExecutingAssembly();
            if (ass != null)
            {
                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(ass.Location);
                return String.Format("Version: {0} ({1})", fvi.ProductVersion, cc);
            }
            //
            return "Version: unknown";
        }
        //
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        private bool checkFirstTime()
        {
            //
            if (true == Properties.Settings.Default.isFirstTime)
            {
                Properties.Settings.Default.isFirstTime = false;
                //
                //Help.ShowHelpIndex(this, helpProvider1.HelpNamespace);
                //MessageBox.Show(labelInfoText.Text, labelInfoCaption.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                //
                return true;
            }
            //
            return false;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Wczytauje pliki z bieżącego katalogu
        /// </summary>
        /// <param name="isLoadNewFile">Czy wczytuje pliki pierwszy raz (nowe)</param>
        /// <returns></returns>
        private bool loadDir()
        {
            string[] dirFiles = null;
            string currentFileExt = "";
            TagLibConnector tlc = new TagLibConnector();
            //
            foreach (string mfe in MusicFilesExtensions)
            {
                if ("" == mfe.Trim()) continue;
                dirFiles = Directory.GetFiles(StartDirectory, @"*" + mfe);
                if (dirFiles.GetLength(0) > 0)
                {
                    currentFileExt = mfe;
                    break;
                }

            }
            //
            LD.Clear();
            for (int i = 0; i < dataGrid1.Columns.Count; i++)
            {
                dataGrid1.Columns[i].Width = DataGridLength.SizeToCells;
            }
            //dataGrid1.ItemsSource = null;
            //dataGrid1.ItemsSource = LD;
            //
            //GetTagsFromFile.GetCapabilities(currentFileExt, out isHandled, out isWritable);
            //
            int failsCount = 0;
            using (new StackedCursorOverride(Cursors.Wait))
            {
                foreach (string fn in dirFiles)
                {
                    string fileName = Path.GetFileNameWithoutExtension(fn);
                    string fileExt = Path.GetExtension(fn);
                    //
                    if (!tlc.ReadTags(fn)) failsCount++;
                    LD.Add(new CData(Path.GetFileName(fn), "", fileName, fileExt, tlc.tagTrack, tlc.tagTitle, tlc.tagArtist, tlc.tagAlbum, tlc.tagYear, tlc.tagGenre));
                }
            }
            //
            setLocaleAfterLoad();
            //
            return true;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private bool setInfoFromPath(string startDirectory)
        {
            DirAlbum = "";// [Year] Album
            DirArtist = ""; // Artist
            string[] dirs = startDirectory.Split('\\');
            if (dirs.GetLength(0) >= 1) DirAlbum = dirs[dirs.GetLength(0) - 1];// [Year] Album
            if (dirs.GetLength(0) >= 2) DirArtist = dirs[dirs.GetLength(0) - 2];// Artist
            //
            window1.Title = DirArtist + "/" + DirAlbum;
            //
            return dirs.GetLength(0) >= 2;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        private void Copy_FileName_2_tagTitle()
        {
            string fn;
            for (int k = 0; k < LD.Count; k++)
            {
                fn = LD[k].FileName;
                //fn = Path.GetFileNameWithoutExtension(fn);
                LD[k].tagTitle = fn;
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void Copy_tagTitle_2_FileName()
        {
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].FileName = Utils.CleanFileName(LD[k].tagTitle);
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void Copy_FileTrack_2_tagTrack()
        {
            string trNo;
            int i;
            for (int k = 0; k < LD.Count; k++)
            {
                trNo = LD[k].FileTrack;
                trNo = trNo.Trim();
                if ("" == trNo) continue;
                if (!int.TryParse(trNo, out i)) continue;
                trNo = GetLegalTrackNumber(trNo);
                //
                LD[k].tagTrack = trNo;
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void Copy_tagTrack_2_FileTrack()
        {
            string trNo;
            for (int k = 0; k < LD.Count; k++)
            {
                trNo = LD[k].tagTrack.Trim();
                if (("" != trNo) && (trNo.Length < 2)) trNo = "0" + trNo;
                LD[k].FileTrack = trNo;
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        private void SetTagTitleAuthor(int nPos, string title, string artist)
        {
            title = title.Trim();
            artist = artist.Trim();
            //
            if ("" == title) return;
            //
            if (nPos >= LD.Count) return;
            //
            LD[nPos].tagTitle = title;
            //
            if ("" != artist)
            {
                LD[nPos].tagArtist = artist;
            }
            //
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------------------------------------------
        private void SetTagAlbum(string album)
        {
            album = album.Trim();
            album = Utils.RemoveTrailingTildes(album);
            //
            if ("" == album) return;
            //
            //
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].tagAlbum = album;
            }
            //
        }
        //--------------------------------------
        private void SetTagArtist(string artist)
        {
            artist = artist.Trim();
            if ("" == artist) return;
            //
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].tagArtist = artist;
            }
        }
        //--------------------------------------
        private void SetTagYear(string year)
        {
            year = year.Trim();
            // biblioteka nie chce zapisywać pustego roku!
            if ("" == year) return;
            {
                int i;
                if (!int.TryParse(year, out i)) return;
                if (i < 1800 && i > DateTime.Now.Year) return;
            }
            //
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].tagYear = year;
            }
        }
        //--------------------------------------
        private void SetTagGenre(string genre)
        {
            genre = genre.Trim();
            //
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].tagGenre = genre;
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void makeWindowsPhoneCompatible()
        {
            DialogBox ibr = new DialogBox() { Title = "Windows Phone", Label = "Album Name:", Text = "" };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;
            //
            string albumName = ibr.Text.Trim();
            //
            if ("" == albumName) return;
            //
            for (int k = 0; k < LD.Count; k++)
            {
                LD[k].FileName = LD[k].tagArtist + " - " + LD[k].tagTitle;
                LD[k].tagTitle = LD[k].tagArtist + " - " + LD[k].tagTitle;
                LD[k].tagAlbum = albumName;
                LD[k].tagArtist = "Various Artists";
                LD[k].tagTrack = Utils.Number2Track(k, LD.Count);
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void Split_tagTitle2tagTitletagAuthor(bool reverse)
        {
            string aa = "";
            string[] at = null;
            string artist = "";
            string title = "";
            //
            for (int k = 0; k < LD.Count; k++)
            {
                aa = LD[k].tagTitle;// "author - title"
                // znamiem podziału może być tylko:'/' i '-'
                at = aa.Split(new char[] { '/' }, 2);
                if (1 == at.GetLength(0))
                {
                    at = aa.Split(new char[] { '-' }, 2);
                }
                if (1 == at.GetLength(0)) continue;
                //
                if (!reverse)
                {
                    artist = at[0].Trim(); title = at[1].Trim();
                }
                else
                {
                    artist = at[1].Trim(); title = at[0].Trim();
                }
                //
                if (("" == artist) || ("" == title)) continue;
                //
                artist = CaseUtils.ToCamelIfNeeded(artist); title = CaseUtils.ToCamelIfNeeded(title);
                //
                LD[k].tagArtist = artist;
                LD[k].tagTitle = title;
                //
            }
        }
        //--------------------------------------
        private void Concat_tagArtisttagTitle2FileName(bool reverse)
        {
            string artist = "";
            string title = "";
            //
            for (int k = 0; k < LD.Count; k++)
            {
                //
                artist = LD[k].tagArtist.Trim();
                title = LD[k].tagTitle.Trim();
                //
                if (("" == artist) && ("" == title)) continue;
                //
                artist = CaseUtils.ToCamelIfNeeded(artist); title = CaseUtils.ToCamelIfNeeded(title);
                //
                if (!reverse)
                {
                    LD[k].FileName = Utils.CleanFileName(artist + " - " + title);
                }
                else
                {
                    LD[k].FileName = Utils.CleanFileName(title + " - " + artist);
                }
            }
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void DoRemove()
        {
            string fnameOld = "", fnameNew = "", regEx = "";
            //
            DialogBox ibr = new DialogBox() { Title = "Remove", Label = "Remove:", Text = "" };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;
            //
            if (!(bool)ibr.DialogResult) return;
            regEx = ibr.Text;
            //
            regEx = regEx.Trim();
            if ("" == regEx) return;
            //
            //
            for (int k = 0; k < LD.Count; k++)
            {
                fnameOld = LD[k].FileName;
                fnameNew = Utils.ReplaceRegular(fnameOld, "", regEx).Trim();
                //
                if ("" == fnameNew)
                {
                    continue;
                }
                //
                if (0 != String.Compare(fnameOld, fnameNew, true))
                {
                    LD[k].FileName = fnameNew;
                }
            }
            //
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void DoClean()
        {
            //
            FileNameConversion fnc = new FileNameConversion();
            //-------------------------------------------------------------------------------------------
            // FileName
            //
            {
                string[] ssTrackSrc = new string[LD.Count];
                string[] ssNamesSrc = new string[LD.Count];
                bool[] isChanged = new bool[LD.Count];
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    ssTrackSrc[kk] = LD[kk].FileTrack.Trim();
                    ssNamesSrc[kk] = LD[kk].FileName.Trim();
                    isChanged[kk] = false;
                }
                //
                splitName(ssTrackSrc, ssNamesSrc, isChanged);
                //
                // specyfika nazw plików, muszą istnieć, składać się tylko z legalnych znaków i być unikalne
                //
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    //
                    ssNamesSrc[kk] = Utils.CleanFileName(ssNamesSrc[kk].Trim());
                    //
                    //
                    if (Utils.isTrackNumberEmpty(ssTrackSrc[kk]) && ("" != ssNamesSrc[kk]))
                    {
                        Int32 n;
                        if (Int32.TryParse(ssNamesSrc[kk], out n))
                        {
                            ssTrackSrc[kk] = ssTrackSrc[kk];
                            ssNamesSrc[kk] = "_" + ssNamesSrc[kk];
                            //
                            isChanged[kk] = true;
                        }
                    }
                    //
                    //
                    if (!Utils.isTrackNumberEmpty(ssTrackSrc[kk]) && ("" == ssNamesSrc[kk]))
                    {
                        ssNamesSrc[kk] = "_" + ssNamesSrc[kk];
                        //
                        isChanged[kk] = true;
                    }
                }
                //
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    if (isChanged[kk])
                    {
                        LD[kk].FileTrack = ssTrackSrc[kk];
                        LD[kk].FileName = ssNamesSrc[kk];
                    }
                    //
                    // ustawienie markera - tylko wtedy, gdy nazwa pliku faktycznie się zmieniła
                    if (0 != String.Compare(LD[kk].Disk_FullFileName, LD[kk].FileTrack + " " + LD[kk].FileName + LD[kk].FileExt, false))
                    {
                        LD[kk].FileName_Changed = true;
                    }
                    else
                    {
                        LD[kk].FileName_Changed = false;
                    }
                    //
                }
                //
            }
            //
            //===========================================================================================
            //
            // tagi
            //
            //-------------------------------------------------------------------------------------------
            // Title
            //
            {
                string[] ssTrackSrc = new string[LD.Count];
                string[] ssNamesSrc = new string[LD.Count];
                bool[] isChanged = new bool[LD.Count];
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    ssTrackSrc[kk] = LD[kk].tagTrack;
                    ssNamesSrc[kk] = LD[kk].tagTitle;
                    isChanged[kk] = false;
                }
                //
                WinylTrackNumbers.CnvIfAny(ssNamesSrc, isChanged);
                //
                splitName(ssTrackSrc, ssNamesSrc, isChanged);
                //
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    if (isChanged[kk])
                    {
                        LD[kk].tagTrack = ssTrackSrc[kk];
                        LD[kk].tagTitle = ssNamesSrc[kk];
                    }
                }
                //
            }
            //
            //-------------------------------------------------------------------------------------------
            // Artist -> to Camel
            //
            {
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    string s = CaseUtils.ToCamelIfNeeded(LD[kk].tagArtist.Trim());
                    if (s != LD[kk].tagArtist) LD[kk].tagArtist = s;
                }
            }
            //
            //-------------------------------------------------------------------------------------------
            // Album -> to Camel
            //
            {
                for (int kk = 0; kk < LD.Count; kk++)
                {
                    string s = CaseUtils.ToCamelIfNeeded(LD[kk].tagAlbum.Trim());
                    if (s != LD[kk].tagAlbum) LD[kk].tagAlbum = s;
                    //
                    s=Utils.RemoveTrailingTildes(LD[kk].tagAlbum);
                    if(s!=LD[kk].tagAlbum)LD[kk].tagAlbum=s;
                }
            }
            //
            //xxxxxxxxxxxxxxxxxxxCData.Sort(LD);
            //
            //
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Dzieli nazwę typu "10 track 1" na elementy: numer scieżki i nazwę
        /// </summary>
        /// <param name="ssTracksSrc"></param>
        /// <param name="ssNamesSrc"></param>
        /// <param name="isChanged"></param>
        /// <returns></returns>
        private bool splitName(string[] ssTracksSrc, string[] ssNamesSrc, bool[] isChanged)
        {
            //
            int kount = ssNamesSrc.Length;
            FileNameConversion fnc = new FileNameConversion();
            //
            //isChanged = new bool[kount];
            string[] ssTracks = new string[kount];
            string[] ssTitles = new string[kount];
            //
            string[] ssTracks2 = new string[kount];
            //
            try
            {
                for (int kk = 0; kk < kount; kk++)
                {
                    ssTracks[kk] = ssTracksSrc[kk].Trim();
                    ssTitles[kk] = ssNamesSrc[kk].Trim();
                }
            }
            catch (Exception ee)
            {
                int i=0;
                MessageBox.Show("");
            }
            //
            //-----------------------------------------------------------------------------------
            //
            // wydobywa numer ze ścieżki
            CleanNames.DoClean(ssTitles, ssTracks, (bool)checkBox_RemoveCommon.IsChecked);
            //
            //for (int kk = 0; kk < kount; kk++)
            Parallel.For(0, kount, kk =>
            {
                // czy faktycznie doszło do zmiany nazwy
                if (0 != String.Compare(ssNamesSrc[kk], ssTitles[kk], false))
                {// case sie liczy
                    isChanged[kk] = true;
                }
                ssNamesSrc[kk] = ssTitles[kk];
                //
                if (Utils.isTrackNumberEmpty(ssTracksSrc[kk]))//tylko, gdy numer pusty przepisywać
                {
                    if (Utils.isTrackNumberEmpty(ssTracks[kk]))
                    {
                        if (!Utils.isTrackNumberEmpty(ssTracks2[kk]))
                        {
                            //ssTracks[kk] = ssTracks2[kk];
                            ssTracksSrc[kk] = ssTracks[kk];
                            //
                            isChanged[kk] = true;
                        }
                    }
                    else
                    {
                        ssTracksSrc[kk] = ssTracks[kk];
                        //
                        isChanged[kk] = true;
                    }
                }
                else if (ssTracksSrc[kk] == ssTracks2[kk])
                {
                    ssTracksSrc[kk] = ssTracks[kk];
                    //
                    isChanged[kk] = true;
                }
                //
                //}//for()
            });
            //
            //
#if false
            // sprawdzenie, czy to nie jest powtórka naumeru "10 10 AAAA"
            // (raczej nie bywa takich zająknięć więcej niż jedno
            {
                string[] _ssTitles = new string[kount];
                string[] _ssTracks = new string[kount];
                Array.Copy(ssNamesSrc, _ssTitles, ssNamesSrc.Length);
                CleanNames.DoClean(ssTitles, ssTracks, checkBox_RemoveCommon.Checked);
                if (Utils.areAllTracksNumbers(_ssTracks))//numery ścieżek wyglądają na poprawne
                {
                    //for (int kk = 0; kk < kount; kk++)
                    Parallel.For(0, kount, kk =>
                    {
                        if (!Utils.isTrackNumberEmpty(ssTracksSrc[kk]) && !Utils.isTrackNumberEmpty(_ssTracks[kk]))
                        {
                            if (ssTracksSrc[kk] == _ssTracks[kk])
                            {
                                ssNamesSrc[kk] = _ssTitles[kk];
                                //
                                isChanged[kk] = true;
                            }
                        }
                        //}
                    });
                }

            }
#endif
            //
            //
            //
            return true;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void DoWrite()
        {
            TagLibConnector tgl = null;
            string nameOld;
            string nameNew;
            //
            //
            using (new StackedCursorOverride(Cursors.Wait))
            {
                for (int k = 0; k < LD.Count; k++)
                {
                    //
                    //
                    nameOld = StartDirectory + @"\" + LD[k].Disk_FullFileName;
                    //
                    if (0 != String.Compare(LD[k].FileExt, CaseUtils.ToLower(LD[k].FileExt), false))// tylko, gdy faktycznie różne nazwy
                    {
                        LD[k].FileExt = CaseUtils.ToLower(LD[k].FileExt);
                        LD[k].FileName_Changed = true;
                        //LD[k].Marker = true;
                    }
                    //
                    nameNew = StartDirectory + @"\";// +dataSet11.DirTable1[k].Number + @" " + dataSet11.DirTable1[k].FileNameNew;
                    if ("" != LD[k].FileTrack)
                    {
                        nameNew += LD[k].FileTrack + @" " + LD[k].FileName + LD[k].FileExt;
                    }
                    else
                    {
                        nameNew += LD[k].FileName + LD[k].FileExt;
                    }
                    //
                    //
                    // wpisujemy tagi jeżeli były zmienione - albo checkBox_UpdateTags zaznaczony, nazwa pliku jeszcze nie zmieniona
                    // albo - tp jest MP3 i ma starego taga na końcu
                    if (Mp3OldTag.isOldTag(nameOld) || LD[k].AnyTagChanged)// tylko, gdy jakieś pole zmienione
                    {
                        tgl = new TagLibConnector();
                        //
                        if (null != tgl)
                        {
                            //
                            tgl.tagTrack = LD[k].tagTrack;
                            tgl.tagTitle = LD[k].tagTitle;
                            tgl.tagArtist = LD[k].tagArtist;
                            tgl.tagAlbum = LD[k].tagAlbum;
                            tgl.tagYear = LD[k].tagYear;
                            tgl.tagGenre = LD[k].tagGenre;
                            //
                            if (tgl.WriteTags(nameOld))
                            {
                                ;
                            }
                        }
                    }
                    //
                    //

                    if (LD[k].FilePartChanged)
                    {
                        try
                        {
                            Utils.Rename(nameOld, nameNew);
                        }
                        catch (Exception e2)
                        {
                            MessageBox.Show(e2.Message, "Rename(" + nameOld + "," + "nameNew" + ")");
                        }
                    }
                    //
                    LD[k].UnChanged();
                }//for
                //
                //
            }
            //
            if (Directory.Exists(StartDirectory))
            {
                WaitingTooLong wtl = new WaitingTooLong(5);
                //this.Enabled = false;
                loadDir();
                //this.Enabled = true;
                wtl.isTooLongBeep(new WindowInteropHelper(this).Handle);
                afterLoad(false);
            }
            //
            //DoClean();
            //
            //
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private string GetLegalTrackNumber(string s)
        {
            if (null == s) return s;
            if ("" == s) return s;
            s = s.Trim();
            if (s.Length < 2) return "0" + s;
            return s;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void RenumberTracks()
        {
            using (new StackedCursorOverride(Cursors.Wait))
            {
                int n = 1;
                for (int k = 0; k < LD.Count; k++)
                {
                    //if (Utils.isTrackNumberEmpty(LD[k].tagTrack)) continue;
                    //
                    LD[k].tagTrack = Utils.Number2Track(n, LD.Count); n++;
                }
            }
            //
            return;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void MultiplyTrackNumber(int nOffset, string multiplier)
        {
            //
            int n = nOffset + int.Parse(multiplier);
            int iv;
            //
            //
            using (new StackedCursorOverride(Cursors.Wait))
            {
                for (int k = 0; k < LD.Count; k++)
                {
                    if (Utils.isTrackNumberEmpty(LD[k].FileTrack)) continue;
                    if (!int.TryParse(LD[k].FileTrack, out iv)) continue;
                    //
                    LD[k].FileTrack = GetLegalTrackNumber(((n * 100) + iv).ToString());
                }
            }
            //
            return;
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private int getMaxTrackNumber()
        {
            int n = 0;
            int iv;
            for (int k = 0; k < LD.Count; k++)
            {
                if (Utils.isTrackNumberEmpty(LD[k].tagTrack)) continue;
                if (!int.TryParse(LD[k].tagTrack, out iv)) continue;
                //
                if (iv > n) n = iv;
            }

            return n;
        }

        //---------------------------------------------------------------------------------------------------------------------------------
        private void changeCase(TextBlock currentCellTextBlock, string columnName, CaseUtils.CASE c)
        {
            if (null != currentCellTextBlock)
            {
                switch (columnName)
                {
                    case "FileName":
                        currentCellTextBlock.Text = CaseUtils.ChangeCase(c, currentCellTextBlock.Text);
                        //((CData)currentCellTextBlock.DataContext).FileName_Changed = true;
                        //((CData)currentCellTextBlock.DataContext).Marker = true;
                        break;
                    case "tagTitle":
                        currentCellTextBlock.Text = CaseUtils.ChangeCase(c, currentCellTextBlock.Text);
                        break;
                    case "tagArtist":
                        currentCellTextBlock.Text = CaseUtils.ChangeCase(c, currentCellTextBlock.Text);
                        break;
                    case "tagAlbum":
                        currentCellTextBlock.Text = CaseUtils.ChangeCase(c, currentCellTextBlock.Text);
                        break;
                    case "tagGenre":
                        currentCellTextBlock.Text = CaseUtils.ChangeCase(c, currentCellTextBlock.Text);
                        break;
                }
            }
            else if ("" != columnName)
            {
                for (int n = 0; n < LD.Count; n++)
                {
                    switch (columnName)
                    {
                        case "FileName":
                            LD[n].FileName = CaseUtils.ChangeCase(c, LD[n].FileName);
                            break;
                        case "tagTitle":
                            LD[n].tagTitle = CaseUtils.ChangeCase(c, LD[n].tagTitle);
                            break;
                        case "tagArtist":
                            LD[n].tagArtist = CaseUtils.ChangeCase(c, LD[n].tagArtist);
                            break;
                        case "tagAlbum":
                            LD[n].tagAlbum = CaseUtils.ChangeCase(c, LD[n].tagAlbum);
                            break;
                        case "tagGenre":
                            LD[n].tagGenre = CaseUtils.ChangeCase(c, LD[n].tagGenre);
                            break;
                    }
                }//for
            }
            //
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private string verifyNumber(string s, int maxDigits)
        {
            if (null == s) s = "";
            s = s.Trim();
            int n;
            if (int.TryParse(s, out n))
            {
                if (s.Length > maxDigits) return s.Substring(s.Length - maxDigits, maxDigits);
                return s;
            }

            return "";
        }
        //---------------------------------------------------------------------------------------------------------------------------------
    }//class
}//namespace
